import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, ViewController, ToastController } from 'ionic-angular';
import { HttpProvider } from '../../providers/http/http';
import { StorageProvider } from '../../providers/storage/storage';
import { DialogProvider } from '../../providers/dialog/dialog';
import { Slides } from 'ionic-angular';
import { HomeDataService } from '../../providers/service/home-data.service';
import { OrderDataService } from '../../providers/service/order-data.service';
import { UserDataService } from '../../providers/service/user-data.service';
import { DeviceInfoDataService } from '../../providers/service/deviceInfo-data.service';
import { Network } from '@ionic-native/network';
import { UserInfoProvider } from '../../providers/user-info/user-info';
import { AppVersion } from '@ionic-native/app-version';
import { InAppBrowser } from '@ionic-native/in-app-browser';
import { App } from 'ionic-angular';
import { BleProvider } from '../../providers/ble/ble';
import { CCPeriodDataService } from '../../providers/service/cCPeriod-data.service';
import { ChargDataService } from '../../providers/service/charg-data.service';
import { ChargstationService } from '../../providers/service/chargstation.service';

declare var $:any;
declare var Swiper:any;
/**
 * Generated class for the HomePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
	selector: 'page-home',
	templateUrl: 'home.html',
})
export class HomePage {
	@ViewChild(Slides) slides: Slides;

	version = '1.0.0';

	constructor(
		public navCtrl: NavController,
		public viewCtrl: ViewController,
		public http: HttpProvider,
		public storage: StorageProvider,
		public dialog: DialogProvider,
		public toastCtrl: ToastController,
		public order: OrderDataService,
		private network: Network,
		public homedata: HomeDataService,
		public user: UserInfoProvider,
		public deviceInfo: DeviceInfoDataService,
		public userData: UserDataService,
		private appVersion: AppVersion,
		private iab: InAppBrowser,
		private app: App,
		public ble: BleProvider,
		public chargdata: ChargDataService,
		public cCPeriodData: CCPeriodDataService,
		public chargstation: ChargstationService, ) { }

	//  这是全局变量(图片数据)
	public data = [
		{
			img: null,
			adsense_type: null,
			urls: null,
		}
	];

	public registerInfo = {
		UserName: '',
		PassWord: '',
		Nickname: ''
	};

	//资讯数据
	public information: Information[] = new Array<Information>();

	// 页数
	page = 1;

	//有网状态=1 断网=0
	Internet = 1;

	// 下拉是否还有数据
	nodata = 0;
	public flag = true;

	// 用户信息
	userInfo: login_info = new login_info();
	local_balance: any;

	ionViewDidLoad() {
		console.log('ionViewDidLoad HomePage');
		if (this.network.type !== 'none' && this.network.type !== '2g') {
			this.getMessage();
			this.getPoint();
			this.getImg(function(e){
				if(e=="true"){
					
			setTimeout(function(){ 
				var swiper = new Swiper('.swiper-container', {
				loop : true,
				pagination: '.swiper-pagination',
//				effect: 'coverflow',
				autoplayDisableOnInteraction : false,
				grabCursor: true,
				centeredSlides: true,
				nextButton: '.swiper-button-next',
				prevButton: '.swiper-button-prev',
				slidesPerView: '2',
				autoplay: 1000,
				coverflow: {
					rotate: 0,// 旋转的角度
					stretch: 0,// 拉伸   图片间左右的间距和密集度
					depth: 0,// 深度   切换图片间上下的间距和密集度
					modifier: 0,// 修正值 该值越大前面的效果越明显
					slideShadows : true,// 页面阴影效果
					},
//				breakpoints: { 
//	                500: {
//	                    slidesPerView: 2,
//	                 },
//	                382: {
//	                    slidesPerView: 2,
//	                 }
//	            }
				});
			
			}, 100);
			
				}
			});
			
		}
		this.appVersion.getVersionNumber().then((ver) => {
			this.version = ver;
			this.getversion();
		});
		
		$(function(){
			var head=$(".index").height();
			$("#home .scroll-content").scroll(function(){
				console.log("ddd");
				var topScr=$("#home .scroll-content").scrollTop();
				if (topScr>head) {
					$(".D-module").addClass("fixed");
					$(".D-information-list").addClass("listTop");
					$(".information").addClass("fixed2");
				}else{
					$(".D-module").removeClass("fixed");
					$(".D-information-list").removeClass("listTop");
					$(".information").removeClass("fixed2");
				}
			})
		})
		
		
	}
	
	async ionViewWillEnter() {
		// this.ble.disconect();
		// this.storage.getStorage("login_info").then(res => {
		//   console.log('ress');
		//   if (res != undefined) {
		//     const access_token = res['access_token'];
		// 	this.http.setAuthorization(access_token);
		//   }
		// });
		this.getLocalBalance();
		
		if (this.network.type !== 'none' && this.network.type !== '2g') {
			this.Internet = 1;
			// this.getMessage();
			await this.uploadOrder();
			await this.uploadDeviceInfo();
			await this.getCCPeriod();
			await this.userData.deleteAll();
			await this.userData.save(this.user.getuserInfo());
			let aer = await this.userData.find((res) => res.key !== '');
			this.getcharging();
			// this.dialog.showAlert('当前保存用户提示', JSON.stringify(aer));
			return;
		}

		// this.dialog.showAlert('网络类型提示', JSON.stringify(this.network.type));
		if (this.network.type === 'none' || this.network.type === '2g') {
			this.toastCtrl.create({
				message: '当前网络环境差，已进入离线模式',
				duration: 2000,
				position: 'top'
			}).present();
			this.Internet = 0;
			let a = await this.homedata.find((information) => information.key !== '');
			this.information = a;
			// for(var i=0;i<a.length;i++){
			// 	this.information[i].titles = a[i]['titles'];
			// 	this.information[i].summary = a[i]['summary'];
			// 	this.information[i].description = a[i]['description'];
			// 	this.information[i].date = a[i]['date'];
			// }

			return;
		}
	}
	
	getLocalBalance() {
    	if (this.flag) {
            this.userInfo = this.user.getuserInfo();
			this.local_balance=this.userInfo.local_balance;
			if(this.local_balance<3){
				this.dialog.showAlert('在手机无网络信号情况下，用户如需正常使用充电桩，敬请使用“本地余额”预先充值', '');
			}
            this.flag = false;
        } else {
            return;
        }
	}
	
	openLink(url) {
    	window.open(url, '_self','location=no');
	}
	skipToChargingBattery() {
		this.navCtrl.push('NodeListPage');
	}
	async skipToChargingAccountPage() {
		// this.navCtrl.parent.select(2);
		this.navCtrl.push('ChargingAccountPage');
	}
	skipToNewsDetail(idiotpmg) {
		if (this.network.type !== 'none' && this.network.type !== '2g') {
			this.Internet = 1;
			this.navCtrl.push('NewsDetailPage', { meg: idiotpmg });
		}
		if (this.network.type === 'none' || this.network.type === '2g') {
			this.dialog.showAlert('网络未连接无法查看，请检查网络连接', '');
		}
	}

	//  获取图片方法
	getImg(back) {
		this.http.postJson('', 'marketing/adsense/getadsense', {
		}, '').then(res => {
			//			console.log(res)
			if (res['status'] == 200) {
				this.getFile_one(res['data'],back);
			}
		});
	}

	//  把数组数据遍历,重新组成新的数据Push到数组里
	getFile_one(data,callback) {
		this.data.splice(0);
//		for (let params of data) {
//			if (params) {//非空校验
		for(var i=0;i<data.length;i++){
			if(data[i]){
				var a = {
					img: this.http.APP_IMG + data[i].url,
					adsense_type: data[i].adsense_type,
					urls: data[i].urls
				};
				this.data.push(a);
				
				if(i==data.length-1){
					console.log("last")
					console.log(i);
					callback("true");
				}
			}

		}

	}

	formatDate = (time: any) => {
		// 格式化日期，获取今天的日期
		const Dates = new Date(time);
		const year: number = Dates.getFullYear();
		const month: any = (Dates.getMonth() + 1) < 10 ? '0' + (Dates.getMonth() + 1) : (Dates.getMonth() + 1);
		const day: any = Dates.getDate() < 10 ? '0' + Dates.getDate() : Dates.getDate();
		return year + '-' + month + '-' + day;
	};


	async getMessage() {

		const res = await this.http.postJson('', 'system/softwen/getsoftwen',
			{
				"tables": "5",
				"file_type_id": "8",
				"soft_wen_type": "6",
				"limit": "2",
				"page": this.page,
				"orderBy": "updated_at DESC, soft_wen_id DESC,created_at DESC"
			}, '').then(res => {
				if (res['status'] == 200) {
					this.getMessage2(res['data']);
					this.nodata = 0;
				}
			});

	}
	async getMessage2(information) {
		//		this.formatDate=data2['data']['created_at'];
		this.information.splice(0);
		for (let message2 of information) {
			if (message2) {
				var b = {
					/*根据提供的接口地址传参数,配置文件在http.ts里查看,里面写的是链接服务器的配置*/
					img2: this.http.APP_IMG + message2.url,
					titles: message2.titles,
					summary: message2.summary,
					description: message2.description,
					date: new Date(parseFloat(message2.updated_at) * 1000)//时间戳的转换要乘上毫秒数


				};
				await this.information.push(b);
			}
		}
		this.homedata.deleteAll();
		for (var i = 0; i < this.information.length; i++) {
			this.homedata.save(this.information[i]);
		}
	}

	//无限滚动(下滑加载)
	async lodeMessage(infiniteScroll, type) {
		this.page++;
		const res = await this.http.postJson('', 'system/softwen/getsoftwen',
			{
				"tables": "5",
				"file_type_id": "8",
				"soft_wen_type": "6",
				"limit": "2",
				"page": this.page,
				"orderBy": "created_at DESC",
			}, '').then(res => {
				if (res['status'] == 200) {

					if (res['data'].length === 0) {
						this.nodata = 1;
						this.page--;
					}
					for (let message2 of res['data']) {

						if (message2) {
							var b = {
								/*根据提供的接口地址传参数,配置文件在http.ts里查看,里面写的是链接服务器的配置*/
								img2: this.http.APP_IMG + message2.url,
								titles: message2.titles,
								summary: message2.summary,
								description: message2.description,
								date: new Date(parseFloat(message2.updated_at) * 1000)//时间戳的转换要乘上毫秒数
							};
							this.information.push(b);
						}
					}
					if (type === 'scroll') {
						setInterval(infiniteScroll.complete(), 500);
					}
				}
			});
	}

	/**
	 * 获取用户信息
	 */
	async login() {
		//   await this.storage.getStorage("login_info").then(res => {
		// 	if(res != undefined) {
		// 		this.userInfo = res;
		// 	}
		// });;
		// console.log(this.userInfo);
		const res = await this.http.postJson('', 'member/member/view?id=' + this.userInfo.member_id, {}, '')
			.then(res => {
				// console.log(res)
				if (res['status'] == 200) {
					res['data']['password'] = this.userInfo.password;
					res['data']['isAutomaticLogon'] = this.userInfo.isAutomaticLogon;
					this.userInfo = res['data'];
					this.user.setuserInfo(this.userInfo);
					// this.storage.saveStorage("login_info", res['data']);
					// this.http.setAuthorization(res['data']['access_token']);//该令牌唯一表示该用户、用户的组和用户的特权。系统使用令牌控制用户可以访问哪些安全对象，并控制用户执行相关系统操作的能力
					// this.navCtrl.push('CenterPage');
				}
			});
	}

	/**
	 * 上传订单
	 */
	async uploadOrder() {
		// 上传订单
		let b = await this.order.find((order) => order.key !== '' && order.upload == 0)//找出订单信息 0没有上传
		if (b.length > 0) {
			for (var i = 0; i < b.length; i++) {
				const key = b[i].key;
				b[i].index = i;
				let res = await this.http.postJson('', 'member/memberch/create', b[i], '');
				// this.dialog.showAlert('order', JSON.stringify(res));
				if (res['status'] === 200) {
					this.order.delete((a) => a.key === key);
				}
				//登录时把订单信息存入服务器
			}
			this.userInfo = this.user.getuserInfo();
			this.login();
		}
	}
/**
   async get(data: Array<any>) {
		let _this = this;
		let _setInterval = setInterval( function(){
			if (data.length>0) {
					const key = data[0].key;
					_this.http.postJson('', 'member/memberch/create', data[0], '').then((res) => {
						_this.dialog.showAlert('order', JSON.stringify(res));
						if (res['status'] === 200) {
							_this.order.delete((a) => a.key === key);
							data.splice(0,1);
						}
					});
					//登录时把订单信息存入服务器
			} else {
				clearInterval(_setInterval);
			}
		}, 500 )

	}
 */
	

	/**
	 * 上传原始设备记录
	 */
	async uploadDeviceInfo() {
		// 上传原始设备记录
		let b = await this.deviceInfo.find((deviceInfo) => deviceInfo.key !== '' && deviceInfo.upload == 0)//找出订单信息 0没有上传
		if (b.length > 0) {
			for (var i = 0; i < b.length; i++) {
				const key = b[i].key;
				let time = new Date((parseInt((b[i].datetime[0] + b[i].datetime[1]), 16) + 2000), (parseInt((b[i].datetime[2] + b[i].datetime[3]), 16) - 1), parseInt((b[i].datetime[4] + b[i].datetime[5]), 16), parseInt((b[i].datetime[6] + b[i].datetime[7]), 16), parseInt((b[i].datetime[8] + b[i].datetime[9]), 16), parseInt((b[i].datetime[10] + b[i].datetime[11]), 16));
				// this.dialog.showAlert('time提示', JSON.stringify(time.getTime().toString().slice(0, 10)));
				let timeLength = time.getTime().toString().slice(0, 10);
				if (timeLength.length < 10) {
					this.deviceInfo.delete((a) => a.key === b[i].key);
					continue;
				}
				// this.dialog.showAlert('info提示', JSON.stringify(b[i]));
				let info = {
					id: b[i].rc_index,
					charge_time_start: time.getTime().toString().slice(0, 10),
					charge_time_end: (time.getTime() + (parseInt(b[i].chargingtime) * 60 * 60 * 1000)).toString().slice(0, 10),
					charge_time_org: parseInt(b[i].chargingtimerequest).toString(),
					// charge_time_start: new Date().getTime().toString().slice(0, 10),
					// charge_time_end: (new Date().getTime() + (parseInt(b[i].chargingtime) * 60 *60) ).toString().slice(0, 10),
					charge_time: parseInt(b[i].chargingtime).toString(),
					power_unit_id: b[i].power_unit_id,
					member_id: parseInt(b[i].userid),
					abnormal: b[i].abnormal,
					notifyInfo: b[i].notifyInfo,
				}
				//登录时把订单信息存入服务器
				const create = await this.http.postJson('', 'business/chargingpr/create', info, '');
				// this.dialog.showAlert('500提示', JSON.stringify(create));
				if (create['status'] === 200) {
					await this.deviceInfo.delete((a) => a.key === b[i].key);
				} else {
					if (create['code'] === 0) {
						let li = await this.deviceInfo.delete((a) => a.key === b[i].key);
						// this.dialog.showAlert('500提示', JSON.stringify(li));
					}
				}
				// if (create['status'] === 500) {
				// 	this.dialog.showAlert('500提示', JSON.stringify(key));
				// 	if (create['code'] === 2) {
				// 		this.order.delete((a) => a.key === key);
				// 	}
				// }

			}
			this.userInfo = this.user.getuserInfo();
			this.login();
		}
	}

	getversion() {
		this.http.postJson('', 'apis/apis/getversion',
			{
				version: this.version,
			}, '')
			.then(res => {
				if (res['status'] == 200) {
					if (res['data']['is_new'] === true) {
						if (res['data']['appUpdate'] === true) {
							this.dialog.showAlert('当前版本已经无法使用，请下载最新!', '').then(success => {
								this.iab.create('https://gx.mzzckj.com/download/', '_system', 'location=yes');
							});
							this.openLoginOut()
							return;
						}


						this.dialog.showConfirm('有新的版本需要更新么?', '').then(success => {
							this.iab.create('https://gx.mzzckj.com/download/', '_system', 'location=yes');
						}, fail => {
							//什么都不做
						});
					}
				}
			});
	}

	getCCPeriod() {
		this.http.postJson('', 'apis/apis/getabnormaltime',
		{}, '')
		.then(async res => {
			if (res['status'] == 200) {
				await this.cCPeriodData.deleteAll();
				await this.cCPeriodData.save({'abnormal_last_time':res['data']['abnormal_last_time'], 'dot_connect_time': res['data']['dot_connect_time']});
			}
		});
	}

	openLoginOut() {
		if (!navigator.onLine) {
			this.app.getRootNav().setRoot('LoginPage');
			return;
		}
		//调用接口的方法
		this.http.postJson('', 'users/member/logout',
			{

			}, '').then(res => {
				if (res['status'] == 200) {
					this.dialog.showConfirm('确定要退出登录吗？', '').then(success => {
						this.app.getRootNav().setRoot('LoginPage');
					}, fail => {
						//什么都不做
					});
				}
			});
	}

	getPoint() {
		let options = {
			enableHighAccuracy: true,  // 是否使用 GPS
			maximumAge: 30000,         // 缓存时间
			timeout: 27000,            // 超时时间
			coorType: 'bd09ll'         // 默认是 gcj02，可填 bd09ll 以获取百度经纬度用于访问百度 API
		  }

		navigator.geolocation.getCurrentPosition((success) => {	}, (error) => { 
			// this.dialog.showConfirm('拒绝使用定位会造成充电桩无法搜索，是否重新开启定位？', '').then(success => {
			// 	this.getPoint();
			//   },
			//   fail => {
  
			//   })
		 }, options);	
	  }

	  async getcharging() {
		this.http.postJson('', 'member/memberch/index?page=' + 1,
		  {
			"where": ["and", ["=", "m_member_charge.member_id", this.userInfo.member_id], ["=", "m_member_charge.states", "1"]],
			"distinct": true,
			"limit": 10,
			"joinwith": ["q_charging_pile"],
			"orderBy": "charge_time_start DESC"
		  }, '').then(res => {
			if (res['status'] == 200) {
				this.chargdata.deleteAll();
				for (var i = 0; i < res['data'].length; i++) {
				  this.chargdata.save(res['data'][i]);
				}
			}
		  });
	  }

}



// getMessage2(data2) {
// 	this.data2.splice(0);
// 	console.log(data2)
// 	for (let message2 of data2) {
// 		if (message2.data) {
// 			var b = {
// 				/*根据提供的接口地址传参数,配置文件在http.ts里查看,里面写的是链接服务器的配置*/
// 				img:  this.http.APP_IMG+message2.url,
// 			    msg : message2.titles,
//         		summary: message2.summary,
//         		description: message2.description,
//         		riqi: message2.created_at,
// 			};
// 			this.data2.push(b);
// 		}
// 	}
// 	console.log(this.data2);
// }




// 引入类定义属性

export class Img {
	img: any;
	img2: any;
	meg: any;
}

export class Information {
	img2: any;
	titles: any;
	summary: any;
	description: any;
	date: any
}

export class login_info {
	member_id: any;
	nickname: any;
	phone: any;
	balance: any;
	local_balance: any;
	member_state: any;
	created_at: any;
	updated_at: any;
	cuser_id: any;
	uuser_id: any;
	is_del: any;
	password: any;
	file_type_id: any;
	access_token: any;
	isAutomaticLogon: any;
}